package demo.service;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.NodeIterator;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.event.jobs.JobUtil;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import demo.inf.BibleUploadService;
import demo.model.UploadStatus;

/**
 * 
 */
@Service
@Component(immediate = true)
public class BibleUploadServiceImpl implements BibleUploadService {

	private static final String BAM = "/bam/";

	private static final Logger log = LoggerFactory
			.getLogger(BibleUploadServiceImpl.class);

	/** The job topic for dropbox job events. */
	public static final String JOB_TOPIC = "demo/bundle/bibleupload/job";

	@Reference
	private ResourceResolverFactory resolverFactory;

	/**
	 * The OSGI event admin used for sending events
	 * 
	 */

	@Reference
	private EventAdmin eventAdmin;

	public boolean process(final String resourcePath, final boolean clear) {

		try {
			log.info("Processing resource {}", resourcePath);
			String resourceType = resolverFactory.getResourceResolver(null)
					.getResource(resourcePath).getResourceType();

			// An event is sent if a file is added to /bam/bibles
			if (resourcePath.startsWith(BAM) && resourceType.equals("nt:file")) {
				final Dictionary<String, Object> props = new Hashtable<String, Object>();
				props.put(JobUtil.PROPERTY_JOB_TOPIC, JOB_TOPIC);
				props.put("resourcePath", resourcePath);
				props.put("clear", clear);
				Event bibleUploadJobEvent = new Event(JobUtil.TOPIC_JOB, props);
				eventAdmin.sendEvent(bibleUploadJobEvent);

				log.info("The upload job has been sent: {}", resourcePath);
				return true;
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return false;
	}

	public List<UploadStatus> getBiblesStatus() {
		return getUploadStatus("/bam/bibles");
	}

	public List<UploadStatus> getXrefsStatus() {
		return getUploadStatus("/bam/xrefs");
	}

	private List<UploadStatus> getUploadStatus(String path) {
		List<UploadStatus> result = new ArrayList<UploadStatus>();

		try {

			Node biblesRoot = resolverFactory.getResourceResolver(null)
					.getResource(path).adaptTo(Node.class);

			NodeIterator bibles = biblesRoot.getNodes();
			while (bibles.hasNext()) {
				Node bible = bibles.nextNode();
				String name = bible.getName();

				result.add(new UploadStatus(name, bible.getPath()));
			}

		} catch (Exception e) {

		}
		return result;
	}
}
